package com.example.pixelyear.sql

import android.content.Context
import com.example.pixelyear.bean.StringBean
import java.lang.ref.WeakReference

class NoteSqlUtils(context: Context) : BaseSqlUtils(context) {

    companion object {
        private lateinit var mInstance: WeakReference<NoteSqlUtils>

        fun getInstance(context: Context): NoteSqlUtils? {
            if (!this::mInstance.isInitialized|| mInstance.get()==null)
                mInstance = WeakReference(NoteSqlUtils(context))
            return mInstance.get()
        }
    }

    fun addNote(data: StringBean) {
        if (!isExists(data.time))
            write.execSQL("insert into " + Sql.noteName + " (date,note) values(?,?)", arrayOf(data.time, data.data))
        else write.execSQL(
            "update " + Sql.noteName + " set note=? where date=?",
            arrayOf(data.data, data.time)
        )
    }

    fun deleteNote(date: String) {
        write.execSQL("delete from " + Sql.noteName + " where date=?", arrayOf(date))
    }

    fun getData(time: String): StringBean? {
        val cursor = read.rawQuery(
            "select * from " + Sql.noteName + " where date = ?",
            arrayOf(time)
        )
        val moveToFirst = cursor.moveToFirst()
        if (moveToFirst) {
            val stringBean = StringBean(
                cursor.getString(cursor.getColumnIndex("date")),
                cursor.getString(cursor.getColumnIndex("note"))
            )
            cursor.close()
            return stringBean
        }
        cursor.close()
        return null
    }

    fun isExists(time: String): Boolean {
        val cursor = read.rawQuery(
            "select * from " + Sql.noteName + " where date = ?",
            arrayOf(time)
        )
        val moveToFirst = cursor.moveToFirst()
        cursor.close()
        return moveToFirst
    }
}